package cc.owoo.godpen.thread;

/**
 * 用于执行任务的线程
 * Created by nimensei
 * 2020-04-15 上午 01:58
 **/
public class ExecuteThread {
    private boolean isExecute;// 是否需要执行
    private boolean isLock;// 线程是否正在运行
    private int delay = 0;// 每次运行的最小间隔
    private Object object;// 传递的值

    private OnExecuteThread on;

    public ExecuteThread() {
    }

    public ExecuteThread(int delay) {
        this.delay = delay;
    }

    public ExecuteThread(OnExecuteThread on) {
        this.on = on;
    }

    public ExecuteThread(OnExecuteThread on, int delay) {
        this.on = on;
        this.delay = delay;
    }

    /**
     * 执行
     */
    public void execute() {
        execute(null);
    }

    public void execute(Object object) {
        isExecute = true;
        this.object = object;
        if (isLock)
            return;
        isLock = true;
        new Thread() {
            public void run() {
                newThread();
            }
        }.start();
    }

    /**
     * 新线程
     */
    private void newThread() {
        while (isExecute) {
            isExecute = false;
            long time = System.currentTimeMillis();
            if (on != null)
                on.run(ExecuteThread.this.object);
            else
                run(object);
            time = System.currentTimeMillis() - time;
            int nowDelay = (int) (delay - time);
            if (nowDelay < 0)
                nowDelay = 0;
            Threads.delay(nowDelay);
        }
        isLock = false;
    }

    /**
     * 设置延迟
     *
     * @param delay 延迟的毫秒值
     */
    public void setDelay(int delay) {
        this.delay = delay;
    }

    /**
     * 获取延迟
     *
     * @return 延迟的毫秒值
     */
    public int getDelay() {
        return delay;
    }

    /**
     * 停止
     */
    public void stop() {
        isExecute = false;
    }

    public void run(Object object) {
    }

    /**
     * 使用接口执行
     */
    public static interface OnExecuteThread {
        public void run(Object object);
    }
}
